package com.junzhiit.nengji.cms.service.impl;

import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.bean.Email;
import com.bainaeco.framework.exception.InvalidArgumentException;

import com.junzhiit.nengji.cms.service.EmailService;
import com.sun.mail.util.MailSSLSocketFactory;

@Service
public class EmailServiceImpl extends BaseServiceImpl implements EmailService {

	@Value("${mail.smtp.port}")
	private String port;
	
	@Value("${mail.smtp.host}")
	private String host;
	
	@Value("${mail.transport.protocol}")
	private String protocol;
	
	@Value("${mail.smtp.auth}")
	private String auth;
	
	@Value("${mail.smtp.enable}")
	private String enable;
	
	@Value("${mail.smtp.username}")
	private String username;
	
	@Value("${mail.smtp.password}")
	private String password;
	
	@Override
	public void sendEmail(Email email) throws Exception {
		boolean isOk = validation(email);
		if(isOk){
			Properties prop = new Properties();
			//协议
	        prop.setProperty("mail.transport.protocol", protocol);
	        //服务器
	        prop.setProperty("mail.smtp.host", host);
	        //端口
	        prop.setProperty("mail.smtp.port", port);
	        //使用smtp身份验证
	        prop.setProperty("mail.smtp.auth", auth);
	        //使用SSL，企业邮箱必需！
	        //开启安全协议
	        MailSSLSocketFactory sf = null;
	        try {
	            sf = new MailSSLSocketFactory();
	            sf.setTrustAllHosts(true);
	        } catch (GeneralSecurityException e) {
	            e.printStackTrace();
	        }
	        prop.put("mail.smtp.ssl.enable", enable);
	        prop.put("mail.smtp.ssl.socketFactory", sf);
	        
	        Session session = Session.getDefaultInstance(prop, new MyAuthenricator(username, password));
	        session.setDebug(true);
	        MimeMessage mimeMessage = new MimeMessage(session);
	        
	        try {
	        	//设置发件人
				mimeMessage.setFrom(new InternetAddress(username,email.getName()));
				//设置收件人
				mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getReceivers()[0]));
				//主题
	            mimeMessage.setSubject(email.getSubject());
	            //时间
	            mimeMessage.setSentDate(new Date());
	            //容器类，可以包含多个MimeBodyPart对象
	            Multipart mp = new MimeMultipart();
	            
	            //MimeBodyPart可以包装文本，图片，附件
	            MimeBodyPart body = new MimeBodyPart();
	            //HTML正文
	            body.setContent(email.getBody(), "text/html; charset=UTF-8");
	            mp.addBodyPart(body);
	            
	            //添加图片&附件
	            if(email.getAttachFile() != null){
	            	body = new MimeBodyPart();
	            	body.attachFile(email.getAttachFile());
	            	mp.addBodyPart(body);
		        }
	            //设置邮件内容
	            mimeMessage.setContent(mp);
	            mimeMessage.saveChanges();
	            Transport.send(mimeMessage);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private class MyAuthenricator extends Authenticator{
		
        String username = null;
        String password = null;
        
        public MyAuthenricator(String username,String passeord){
            this.username = username;
            this.password = passeord;
        }
        
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    }
	
	private boolean validation(Email email){
		boolean isOk = true;
		if(ArrayUtils.isEmpty(email.getReceivers())){
			isOk = false;
			throw new InvalidArgumentException("Receivers is empty.");
		} else if(StringUtils.isBlank(email.getSubject())){
			isOk = false;
			throw new InvalidArgumentException("Subject is blank.");
		} else if(StringUtils.isBlank(email.getBody())){
			isOk = false;
			throw new InvalidArgumentException("Body is blank.");
		}
		return isOk;
	}
	
}
